var unit_dict = dictCtrl.dictionary.translate("measureUnit");
var dutymode_dict = dictCtrl.dictionary.translate("dutymode");
var nation_dict = dictCtrl.dictionary.translate("nation");
$.views.converters({
	converterDocuCode:function(value){
		return "需要转码:"+value;
	},
	converterContainerMd:function(value){
		return "需要转码:"+value;
	},
	converterDutymode: function(value) {
		if(!value){
			return "";
		}
		for(index in dutymode_dict){
			var v = dutymode_dict[index];
			if(v.dictCode == value){
				return v.dictName;
			}
		}
		return  "未知类型("+value+")";
	},
	converterNation: function(value) {
		if(!value){
			return "";
		}
		for(index in nation_dict){
			var v = nation_dict[index];
			if(v.dictCode == value){
				return v.dictName;
			}
		}
		return  "未知类型("+value+")";
	}
});

Array.prototype.remove=function(dx) {
    if(isNaN(dx)||dx>this.length){return false;}
    for(var i=0,n=0;i<this.length;i++)
    {
        if(this[i]!=this[dx])
        {
            this[n++]=this[i]
        }
    }
    this.length-=1
}

var OP_NUKNOW=-1
var OP_NEW =0;
var OP_EDIT =1;
var OP_DEL =2;

var decHeadEditCtrl = new XFApp.client();
XFApp.client.prototype.strToObj=function(str){
	str = str.replace(/&/g,"','");
	str = str.replace(/=/g,"':'");
	str = "({'"+str +"'})";
	obj = eval(str);
	return obj;
}

XFApp.client.prototype.logi= function(msg){
	console.log(msg);
}

XFApp.client.prototype.decHeadEdit = {
	editId: '',//当前编辑的信息
	successCode : "10000",
	loadingDialog: {},
	urlItems : {
		//提交企业备案
		submitDecRecordURL: basePath + '/decManage/save',
		submitDecRecordJsonURL: basePath + '/decManage/saveDecJson'
	},
	initView: function(){
		var _this = this;
		_this.enterFormValidate();
		decHeadEditCtrl.decListEdit.queryDeclistByDecHead(_this.editId);
        decHeadEditCtrl.decLicenseEdit.queryDecLicenseByDecHead(_this.editId);
		decHeadEditCtrl.decContainerEdit.queryDecContainerByDecHead(_this.editId);
	},
	submitDec: function(){
		var _this = this;
		if(!$("#enterpriseForm").validate().form()){
			return;
		}
		var decHeadData = _this.getDecHeadFormData();
		_this.doSubmitDec(decHeadData);
	},
	submitDecJson: function(){
		var _this = this;
		if(!$("#enterpriseForm").validate().form()){
			return;
		}
		var decHeadData = _this.getDecHeadFormData();
		_this.doSubmitDecJson(decHeadData);
		//decHeadEditCtrl.logi(JSON.stringify(decHeadData));
	},
	doSubmitDec: function(data){
		var _this = this;
		_this.loadingDialog = webDialogUtil.loading('正在暂存，请稍后...');
		data.id = data.decHead_id;
		$.ajax({
			url : _this.urlItems.submitDecRecordURL,
			secureuri : false,
			data:data,
			dataType : 'json',
			success : function(data) {
				_this.loadingDialog.close();
				if (data.code == _this.successCode) {
                    if(data.result.id && decHeadEditCtrl.decListEdit.declists.length > 0){
                        decHeadEditCtrl.decListEdit.submitShopData(data.result.id);
                    }
                    if(data.result.id && decHeadEditCtrl.decLicenseEdit.decLicenses.length > 0){
                        decHeadEditCtrl.decLicenseEdit.submitLicenseData(data.result.id);
                    }
                    if(data.result.id && decHeadEditCtrl.decContainerEdit.decContainers.length > 0){
                        decHeadEditCtrl.decContainerEdit.submitContainerData(data.result.id);
                    }
                    window.webDialogUtil.alert("提示","暂存成功");
                    //_this.refreshEnterForm();
                } else {
					window.webDialogUtil.alert("提示",data.msg);
				}
				_this.refreshEnterForm();
			},
			error : function(data, status, e){
				window.webDialogUtil.alert("提示",data.msg);
				_this.loadingDialog.close();
			}
		});
	},
    doSubmitDecJson: function(data){
		var _this = this;
		_this.loadingDialog = webDialogUtil.loading('正在暂存，请稍后...');
		data={entryid:100000};
		$.ajax({
			url : _this.urlItems.submitDecRecordJsonURL,
			secureuri : false,
			//data: data,
			data:JSON.stringify(data),
			dataType : 'json',
			contentType:"application/json",
			success : function(data) {
				_this.loadingDialog.close();
				if (data.code == _this.successCode) {
					if(data.result.id && decHeadEditCtrl.decListEdit.declists.length > 0){
						decHeadEditCtrl.decListEdit.submitShopData(data.result.id);
                        decHeadEditCtrl.decLicenseEdit.submitLicenseData(data.result.id);
					}else{
						window.webDialogUtil.alert("提示","暂存成功");
						//_this.refreshEnterForm();
					}
				} else {
					_this.loadingDialog.close();
					window.webDialogUtil.alert("提示",data.msg);
				}
			},
			error : function(data, status, e){
				window.webDialogUtil.alert("提示",data.msg);
				_this.loadingDialog.close();
			}
		});
	},
	getDecHeadFormData: function(){
	 	var _this = this;
	 	var decHeadData = $('#enterpriseForm').serialize();
		decHeadData = decodeURIComponent(decHeadData,true);
		decHeadData = decHeadEditCtrl.strToObj(decHeadData);
	 	/*$("#enterpriseForm input[type='checkbox']").each(function(index,obj){
	 		if(obj.checked){
				decHeadData[obj.name] = 'Y';
	 		}else{
				decHeadData[obj.name] = 'N';
	 		}
	 		//decHeadEditCtrl.logi(enterpriseData);
	 	});*/
	 	return decHeadData;
	 },
	 enterFormValidate: function(){
		$("#enterpriseForm").validate(enterpriseValidate);
		$("#enterpriseForm").validate();
	 },
	//？？？？？czc
	 refreshEnterForm:function(){
	 	$('#filetd').children().remove();
	 	$('#filetd').append('<label class="control-label"></label><input id="fileinput" name="attach" type="file" multiple class="file-loading">');
	 	_this.initUploadPlugin();
	 	$("#enterpriseForm input[type='checkbox']").each(function(index,el){
			el.checked = false
		});
		$("#enterpriseForm input").each(function(index,el){
			//decHeadEditCtrl.logi(el.name);
			if(el.id=='fileinput'){
				//$('#fileinput').fileinput('clear');
			}else{
				el.value = '';
			}
		});
		$('#comments').html('');
		customscodeUtil.setDefaultCustom("customSelect",pspName);
	 },
	/**
	 * 绑定页面事件
	 */
	event : function(){
		var _this = this;
		$('#saveEnterpriseBtn').on('click',function(){
			_this.submitDec();
			//_this.submitDecJson();
		});
	}
}

XFApp.client.prototype.decListEdit = {
	declists: new Array(),
	decListPage: '',
	successCode : "10000",
	loadingDialog: {},
	urlItems : {
		queryPageURLDeclistByHeadID: basePath + '/decManage/queryPageDecList',
		saveShopUrl: basePath + '/decManage/saveDecList'
	},
	/**
	 * 查询表体
	 */
	queryDeclistByDecHead: function(id){
		_this = this;
		var queryParams = {decHeadId: id};
		if(!!_this.decListPage){
			_this.decListPage.page("remote",0,queryParams);
		}else{
			_this.decListPage = $("#decListPage").page({
				pageSize : 5000,
				remote: {
					url: _this.urlItems.queryPageURLDeclistByHeadID,
					params: queryParams,
					success: function (data, pageIndex) {
						if(data.code==_this.successCode){
							var pageResult = data.result;
							$("#decListGrid").html($("#decListDataTmpl").render(pageResult.itemList));
							_this.declists = pageResult.itemList;
							for(var i = 0 ; i < _this.declists.length; i ++){
								_this.declists[i].op = OP_NUKNOW;
							}
						}else{
							window.webDialogUtil.alert("提示",data.msg);
						}
					},
					error : function(){
						window.webDialogUtil.alert("提示",data.msg);
					}
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});
		}
	},
	findDecList:function(gno){
		for(var i = 0 ; i < this.declists.length; i ++){
			if(this.declists[i].gno == gno){
				return this.declists[i];
			}
		}
		return null;
	},
	findDecListIndex:function(gno){
		for(var i = 0 ; i < this.declists.length; i ++){
			if(this.declists[i].gno == gno){
				return i;
			}
		}
		return -1;
	},
	//没地方使用了
	removeDecListFromDataModel:function(gno){
		index = this.findDecListIndex(gno);
		if(index>=0){
			this.declists.splice(index,1);
		}
	},
	//真正需要删除的数据，界面做删除标记，提交到服务端删除数据
	markRemoveDecListFromDataModel:function(gno){
		shopData = this.findDecList(gno);
		if(shopData!=null){
			shopData.op=OP_DEL;
		}
	},
	//把DecList信息显示到界面列表中（删除的数据不再显示）
	showDecListInTable:function(declistArray){
		var declistArrayForShow= new Array();
		for(var i = 0 ; i < declistArray.length; i ++){
			if(declistArray[i].op!=OP_DEL){
				declistArrayForShow.push(declistArray[i]);
			}
		}
		$("#decListGrid").html($("#decListDataTmpl").render(declistArrayForShow));
	},
	delDecList : function(id){
		var _this = this;
		webDialogUtil.simpleConfrimAlert('是否确认删除？', function(){
			_this.markRemoveDecListFromDataModel(id);
			_this.showDecListInTable(_this.declists);
		});
	},
	getMaxGNo:function(){//获取界面GNO最大值
		var max = 0;
		for(var i = 0 ; i < this.declists.length; i ++){
			if(this.declists[i].gno > max){
				max = this.declists[i].gno;
			}
		}
		return max;
	},
	loadDecListDictData:function(){
		dictCtrl.dictionary.load("nation","origincountry","origincountryname");
		dictCtrl.dictionary.load("nation","destinationcountry","destinationcountryname");

		dictCtrl.dictionary.load("measureUnit","gunit","gunitname");
		dictCtrl.dictionary.load("measureUnit","firstunit","firstunitname");
		dictCtrl.dictionary.load("measureUnit","secondunit","secondunitname");
		dictCtrl.dictionary.load("dutymode","dutymode","dutymodename");
	},
	showAdd: function(){
		var _this = this;
		$("#decListForm")[0].reset();
		//$("#decList_op").val(OP_NEW);
		//$("#decHeadId_decListBak").val(_this.editId);
		$('#gno').val(parseInt(_this.getMaxGNo())+1);
		_this.loadDecListDictData();
		$('#choose_sku_modal').modal();
	},
	showEditDecList : function(id){
		var _this = this;
		shop  = _this.findDecList(id);
		_this.decListDataToForm(shop);
		//$("#decList_op").val(OP_EDIT);
		$('#gno_bak').val(shop.gno);//记录历史记录编号
		_this.loadDecListDictData();
		$('#choose_sku_modal').modal();
	},
	decListDataToForm:function(decList){
		var  arr = Object.keys(decList);
		for(var i = 0 ; i < arr.length; i ++){
			$('#'+arr[i]).val(decList[arr[i]]);
		}
	},
	formTodecListData:function(decList){
		var  arr = Object.keys(decList);
		for(var i = 0 ; i < arr.length; i ++){
			if($('#'+arr[i]).length==1){
				decList[arr[i]]=$('#'+arr[i]).val();
			}
		}
		return decList;
	},
	/**
	 * 提交店铺数据
	 */
	submitShopData: function(decheadid){
		var _this = this;
		for(var i = 0 ; i < _this.declists.length; i ++){
			_this.declists[i].decHeadId = decheadid;
		}
		$.ajax({
			type:"POST",
			url:_this.urlItems.saveShopUrl,
			dataType:"json",
			contentType:"application/json",
			data:JSON.stringify(_this.declists),
			success:function(data){
				if (data.code == _this.successCode) {
					//window.webDialogUtil.alert("提示","暂存成功");
					//_this.loadingDialog.close();
				}
			}
		});
	},
	/**
	 * (新增保存，编辑保存)
	 */
	saveFormData: function(){
		var _this = this;
		if(!$("#decListForm").validate().form()){
			return;
		}
		var shopData = $('#decListForm').serialize();
		shopData = decodeURIComponent(shopData,true);
		shopData = decHeadEditCtrl.strToObj(shopData);
		index1 = _this.findDecListIndex(shopData.gno);
		if(index1<0){
			//新增
			shopData.op = OP_NEW;
			//_this.declists.splice(index2,0,shopData);
			//_this.declists.push(shopData);
			_this.declists.unshift(shopData);
		}else{
			//修改
			shopData= _this.findDecList($('#gno').val());
			if(shopData.op != OP_NEW){
				shopData.op = OP_EDIT;
			}
			shopData = _this.formTodecListData(shopData);
		}
		_this.showDecListInTable(_this.declists);
		$("#decListForm")[0].reset();
		$('#choose_sku_modal').modal('hide');
	},
	event : function(){
		var _this = this;
		$('#showAddStoreDailog').on("click",function(){
			_this.showAdd();
		});
		$('#saveDecListBtn').on('click',function(){
			_this.saveFormData();
		});
	}
}



XFApp.client.prototype.decLicenseEdit = {
    decLicenses: new Array(),
    decLicensePage: '',
    successCode : "10000",
    loadingDialog: {},
    urlItems : {
        queryPageURLDecLicenseByHeadID: basePath + '/decManage/queryPageDeclicenses',
        saveLicenseUrl: basePath + '/decManage/saveDeclicenses'
    },
    /**
     * 查询表体
     */
    queryDecLicenseByDecHead: function(id){
        _this = this;
        var queryParams = {decheadid: id};
        if(!!_this.decLicensePage){
            _this.decLicensePage.page("remote",0,queryParams);
        }else{
            _this.decLicensePage = $("#decLicensePage").page({
                pageSize : 5000,
                remote: {
                    url: _this.urlItems.queryPageURLDecLicenseByHeadID,
                    params: queryParams,
                    success: function (data, pageIndex) {
                        if(data.code==_this.successCode){
                            var pageResult = data.result;
                            $("#decLicenseGrid").html($("#decLicenseDataTmpl").render(pageResult.itemList));
                            _this.decLicenses = pageResult.itemList;
                            for(var i = 0 ; i < _this.decLicenses.length; i ++){
                                _this.decLicenses[i].op = OP_NUKNOW;
                            }
                        }else{
                            window.webDialogUtil.alert("提示",data.msg);
                        }
                    },
                    error : function(){
                        window.webDialogUtil.alert("提示",data.msg);
                    }
                },
                firstBtnText : '首页',
                lastBtnText : '尾页',
                prevBtnText : '上一页',
                nextBtnText : '下一页',
                showInfo : true,
                showJump : true,
                jumpBtnText : '跳转',
                showPageSizes : true,
                infoFormat : '共{pageCount}页'
            });
        }
    },
    /**
     * 提交店铺数据
     */
    submitLicenseData: function(decheadid){
        var _this = this;
        for(var i = 0 ; i < _this.decLicenses.length; i ++){
            _this.decLicenses[i].decheadid = decheadid;
        }
        $.ajax({
            type:"POST",
            url:_this.urlItems.saveLicenseUrl,
            dataType:"json",
            contentType:"application/json",
            data:JSON.stringify(_this.decLicenses),
            success:function(data){
                if (data.code == _this.successCode) {
                    //window.webDialogUtil.alert("提示","暂存成功");
                }
            }
        });
    },
    findDecLicenseByCertCode:function(certcode){
        for(var i = 0 ; i < this.decLicenses.length; i ++){
            if(this.decLicenses[i].certcode == certcode){
                return this.decLicenses[i];
            }
        }
        return null;
    },
    findDecLicenseIndexByCertCode:function(certcode){
        for(var i = 0 ; i < this.decLicenses.length; i ++){
            if(this.decLicenses[i].certcode == certcode){
                return i;
            }
        }
        return -1;
    },
    findDecLicenseById:function(id){
        for(var i = 0 ; i < this.decLicenses.length; i ++){
            if(this.decLicenses[i].id == id){
                return this.decLicenses[i];
            }
        }
        return null;
    },
    findDecLicenseIndexById:function(id){
        for(var i = 0 ; i < this.decLicenses.length; i ++){
            if(this.decLicenses[i].id == id){
                return i;
            }
        }
        return -1;
    },
    removeDecLicenseFromDataModel:function(id){
        index = this.findDecLicenseIndexById(id);
        if(index>=0){
            this.decLicenses.splice(index,1);
        }
    },
    //真正需要删除的数据，界面做删除标记，提交到服务端删除数据
    markRemoveDecLicenseFromDataModel:function(id){
        shopData = this.findDecLicenseById(id);
        if(shopData!=null){
            shopData.op=OP_DEL;
        }
    },
    //把DecList信息显示到界面列表中（删除的数据不再显示）
    showDecLicenseInTable:function(decLicenseArray){
        var decLicenseArrayForShow= new Array();
        for(var i = 0 ; i < decLicenseArray.length; i ++){
            if(decLicenseArray[i].op!=OP_DEL){
                decLicenseArrayForShow.push(decLicenseArray[i]);
            }
        }
        $("#decLicenseGrid").html($("#decLicenseDataTmpl").render(decLicenseArrayForShow));
    },
    getMaxId:function(){//获取界面GNO最大值
        var max = 0;
        for(var i = 0 ; i < this.decLicenses.length; i ++){
            if(this.decLicenses[i].id > max){
                max = this.decLicenses[i].id;
            }
        }
        return max;
    },
    loadDecLicenseDictData:function(){
        /*dictCtrl.dictionary.load("nation","origincountry","origincountryname");
         dictCtrl.dictionary.load("nation","destinationcountry","destinationcountryname");
         dictCtrl.dictionary.load("measureUnit","gunit","gunitname");
         dictCtrl.dictionary.load("measureUnit","firstunit","firstunitname");
         dictCtrl.dictionary.load("measureUnit","secondunit","secondunitname");
         dictCtrl.dictionary.load("dutymode","dutymode","dutymodename");*/
    },
    showAddLicense : function(){
        var _this = this;
        $("#decLicenseForm")[0].reset();
        $("#license_op").val(OP_NEW);
        //$("#decHeadId_decListBak").val(_this.editId);
        _this.loadDecLicenseDictData();
        $('#license_modal').modal();
    },
    showEditDecLicense : function(id){
        var _this = this;
        license  = _this.findDecLicenseById(id);
        orgOp=license.op;
        license.op = OP_EDIT;
        _this.decLicenseDataToForm(license);
        license.op=orgOp;
        _this.loadDecLicenseDictData();
        $('#license_modal').modal();
    },
    decLicenseDataToForm:function(decLicense){
        var  arr = Object.keys(decLicense);
        for(var i = 0 ; i < arr.length; i ++){
            $('#license_'+arr[i]).val(decLicense[arr[i]]);
        }
    },
    fixLicenseFromformData:function(license){
        var  arr = Object.keys(license);
        for(var i = 0 ; i < arr.length; i ++){
            if($('#license_'+arr[i]).length==1){
                license[arr[i]]=$('#license_'+arr[i]).val();
            }
        }
        return license;
    },
    //去掉所有属性的 license_ 前缀
    formTodecLicenseData:function(formLicense){
        var  arr = Object.keys(formLicense);
        var licenseData =new Object;
        for(var i = 0 ; i < arr.length; i ++){
            if(arr[i].indexOf("license_")==0){
                newArr =arr[i].substr(8);
                licenseData[newArr] = formLicense[arr[i]];
            }
        }
        return licenseData;
    },
    delDecLicense : function(id){
        var _this = this;
        webDialogUtil.simpleConfrimAlert('是否确认删除？', function(){
            licenseData= _this.findDecLicenseById(id);
            if(licenseData.op==OP_NEW){
                _this.removeDecLicenseFromDataModel(id);
            }else{
                _this.markRemoveDecLicenseFromDataModel(id);
            }
            _this.showDecLicenseInTable(_this.decLicenses);
        });
    },
    /**
     * (新增保存，编辑保存)
     */
    saveLicenseFormData: function(){
        var _this = this;
        if(!$("#decLicenseForm").validate().form()){
            return;
        }
        var formLicenseData = $('#decLicenseForm').serialize();
        formLicenseData = decodeURIComponent(formLicenseData,true);
        formLicenseData = decHeadEditCtrl.strToObj(formLicenseData);
        index1 = _this.findDecLicenseIndexByCertCode(formLicenseData.license_certcode);
        if(formLicenseData.license_op==OP_NEW){
            //新增
            if(index1>=0){
                alert("exist");
                return;
            }
            //formLicenseData.license_op=OP_NEW;
            formLicenseData.license_id = _this.getMaxId()+1;
            licenseData = _this.formTodecLicenseData(formLicenseData);
            _this.decLicenses.unshift(licenseData);
        }else{
            //修改
            if(formLicenseData.license_op != OP_NEW){
                formLicenseData.license_op = OP_EDIT;
            }
            licenseOri = _this.findDecLicenseById(formLicenseData.license_id);
            orgOp=licenseOri.op;
            index2 = _this.findDecLicenseIndexByCertCode(licenseOri.certcode);
            if((index1>=0)&&(index2!=index1)){
                alert("exist");
                return;
            }
            _this.fixLicenseFromformData(licenseOri);
            //如果是新增记录，编辑后，还是新增记录
            if(orgOp==OP_NEW){
                licenseOri.op =OP_NEW;
            }
        }
        _this.showDecLicenseInTable(_this.decLicenses);
        $("#decLicenseForm")[0].reset();
        $('#license_modal').modal('hide');
    },
    event : function(){
        var _this = this;
        $('#showAddLicenseDailog').on("click",function(){
            _this.showAddLicense();
        });
        $('#saveLicenseBtn').on('click',function(){
            _this.saveLicenseFormData();
        });
    }
}

// -------container-------------


XFApp.client.prototype.decContainerEdit = {
    decContainers: new Array(),
    decContainerPage: '',
    successCode : "10000",
    loadingDialog: {},
    urlItems : {
        queryPageURLDecContainerByHeadID: basePath + '/decManage/queryPageDecContainers',
        saveContainerUrl: basePath + '/decManage/saveDecContainers'
    },
    /**
     * 查询表体
     */
    queryDecContainerByDecHead: function(id){
        _this = this;
        var queryParams = {decheadid: id};
        if(!!_this.decContainerPage){
            _this.decContainerPage.page("remote",0,queryParams);
        }else{
            _this.decContainerPage = $("#containerPage").page({
                pageSize : 5000,
                remote: {
                    url: _this.urlItems.queryPageURLDecContainerByHeadID,
                    params: queryParams,
                    success: function (data, pageIndex) {
                        if(data.code==_this.successCode){
                            var pageResult = data.result;
                            $("#decContainerGrid").html($("#decContainerDataTmpl").render(pageResult.itemList));
                            _this.decContainers = pageResult.itemList;
                            for(var i = 0 ; i < _this.decContainers.length; i ++){
                                _this.decContainers[i].op = OP_NUKNOW;
                            }
                        }else{
                            window.webDialogUtil.alert("提示",data.msg);
                        }
                    },
                    error : function(){
                        window.webDialogUtil.alert("提示",data.msg);
                    }
                },
                firstBtnText : '首页',
                lastBtnText : '尾页',
                prevBtnText : '上一页',
                nextBtnText : '下一页',
                showInfo : true,
                showJump : true,
                jumpBtnText : '跳转',
                showPageSizes : true,
                infoFormat : '共{pageCount}页'
            });
        }
    },
    /**
     * 提交店铺数据
     */
    submitContainerData: function(decheadid){
        var _this = this;
        for(var i = 0 ; i < _this.decContainers.length; i ++){
            _this.decContainers[i].decheadid = decheadid;
        }
        $.ajax({
            type:"POST",
            url:_this.urlItems.saveContainerUrl,
            dataType:"json",
            contentType:"application/json",
            data:JSON.stringify(_this.decContainers),
            success:function(data){
                if (data.code == _this.successCode) {
                    //window.webDialogUtil.alert("提示","暂存成功");
                }
            }
        });
    },
    /*findDecContainerByCertCode:function(certcode){
        for(var i = 0 ; i < this.decContainers.length; i ++){
            if(this.decContainers[i].certcode == certcode){
                return this.decContainers[i];
            }
        }
        return null;
    },*/
    findDecContainerIndexByContainerId:function(containerid){
        for(var i = 0 ; i < this.decContainers.length; i ++){
            if(this.decContainers[i].containerid== containerid){
                return i;
            }
        }
        return -1;
    },
    findDecContainerById:function(id){
        for(var i = 0 ; i < this.decContainers.length; i ++){
            if(this.decContainers[i].id == id){
                return this.decContainers[i];
            }
        }
        return null;
    },
    findDecContainerIndexById:function(id){
        for(var i = 0 ; i < this.decContainers.length; i ++){
            if(this.decContainers[i].id == id){
                return i;
            }
        }
        return -1;
    },
    removeDecContainerFromDataModel:function(id){
        index = this.findDecContainerIndexById(id);
        if(index>=0){
            this.decContainers.splice(index,1);
        }
    },
    //真正需要删除的数据，界面做删除标记，提交到服务端删除数据
    markRemoveDecContainerFromDataModel:function(id){
        shopData = this.findDecContainerById(id);
        if(shopData!=null){
            shopData.op=OP_DEL;
        }
    },
    //把DecList信息显示到界面列表中（删除的数据不再显示）
    showDecContainerInTable:function(decContainerArray){
        var decContainerArrayForShow= new Array();
        for(var i = 0 ; i < decContainerArray.length; i ++){
            if(decContainerArray[i].op!=OP_DEL){
                decContainerArrayForShow.push(decContainerArray[i]);
            }
        }
        $("#decContainerGrid").html($("#decContainerDataTmpl").render(decContainerArrayForShow));
    },
    getMaxId:function(){//获取界面ID最大值
        var max = 0;
        for(var i = 0 ; i < this.decContainers.length; i ++){
            if(this.decContainers[i].id > max){
                max = this.decContainers[i].id;
            }
        }
        return max;
    },
    loadDecContainerDictData:function(){

    },
    showAddContainer : function(){
        var _this = this;
        $("#decContainerForm")[0].reset();
        $("#container_op").val(OP_NEW);
        //$("#decHeadId_decListBak").val(_this.editId);
        _this.loadDecContainerDictData();
        $('#container_modal').modal();
    },
    showEditDecContainer : function(id){
        var _this = this;
        Container  = _this.findDecContainerById(id);
        orgOp=Container.op;
        Container.op = OP_EDIT;
        _this.decContainerDataToForm(Container);
        Container.op=orgOp;
        _this.loadDecContainerDictData();
        $('#container_modal').modal();
    },
    decContainerDataToForm:function(decContainer){
        var  arr = Object.keys(decContainer);
        for(var i = 0 ; i < arr.length; i ++){
            $('#container_'+arr[i]).val(decContainer[arr[i]]);
        }
    },
    fixContainerFromformData:function(Container){
        var  arr = Object.keys(Container);
        for(var i = 0 ; i < arr.length; i ++){
            if($('#container_'+arr[i]).length==1){
                Container[arr[i]]=$('#container_'+arr[i]).val();
            }
        }
        return Container;
    },
    //去掉所有属性的 Container_ 前缀
    formTodecContainerData:function(formContainer){
        var  arr = Object.keys(formContainer);
        var ContainerData =new Object;
        for(var i = 0 ; i < arr.length; i ++){
            if(arr[i].indexOf("container_")==0){
                newArr =arr[i].substr(10);
                ContainerData[newArr] = formContainer[arr[i]];
            }
        }
        return ContainerData;
    },
    delDecContainer : function(id){
        var _this = this;
        webDialogUtil.simpleConfrimAlert('是否确认删除？', function(){
            ContainerData= _this.findDecContainerById(id);
            if(ContainerData.op==OP_NEW){
                _this.removeDecContainerFromDataModel(id);
            }else{
                _this.markRemoveDecContainerFromDataModel(id);
            }
            _this.showDecContainerInTable(_this.decContainers);
        });
    },
    /**
     * (新增保存，编辑保存)
     */
    saveContainerFormData: function(){
        var _this = this;
        if(!$("#decContainerForm").validate().form()){
            return;
        }
        var formContainerData = $('#decContainerForm').serialize();
        formContainerData = decodeURIComponent(formContainerData,true);
        formContainerData = decHeadEditCtrl.strToObj(formContainerData);
        index1 = _this.findDecContainerIndexByContainerId(formContainerData.container_containerid);
        if(formContainerData.container_op==OP_NEW){
            //新增
            if(index1>=0){
                alert("exist");
                return;
            }
            //formContainerData.Container_op=OP_NEW;
            formContainerData.container_id = _this.getMaxId()+1;
            ContainerData = _this.formTodecContainerData(formContainerData);
            _this.decContainers.unshift(ContainerData);
        }else{
            //修改
            if(formContainerData.container_op != OP_NEW){
                formContainerData.container_op = OP_EDIT;
            }
            ContainerOri = _this.findDecContainerById(formContainerData.container_id);
            orgOp=ContainerOri.op;
            index2 = _this.findDecContainerIndexByContainerId(ContainerOri.containerid);
            if((index1>=0)&&(index2!=index1)){
                alert("exist");
                return;
            }
            _this.fixContainerFromformData(ContainerOri);
            //如果是新增记录，编辑后，还是新增记录
            if(orgOp==OP_NEW){
                ContainerOri.op =OP_NEW;
            }
        }
        _this.showDecContainerInTable(_this.decContainers);
        $("#decContainerForm")[0].reset();
        $('#container_modal').modal('hide');
    },
    event : function(){
        var _this = this;
        $('#showAddContainerDailog').on("click",function(){
            _this.showAddContainer();
        });
        $('#saveContainerBtn').on('click',function(){
            _this.saveContainerFormData();
        });
    }
}

//--------------------------

$(function(){
	dictCtrl.dictionary.load("fileType","dictid","dictname");
	dictCtrl.dictionary.load("customsCode","ieport","ieportname");
	dictCtrl.dictionary.load("transferMode","trafmode","trafmodename");
	dictCtrl.dictionary.load("cutmode","cutmode","cutmodename");
	dictCtrl.dictionary.load("qptradeMode","trademode","trademodename");
	dictCtrl.dictionary.load("paymentmark","paymentmark","paymentmarkname");
	dictCtrl.dictionary.load("wrapType","wraptype","wraptypename");
	dictCtrl.dictionary.load("transmode","transmode","transmodename");
	dictCtrl.dictionary.load("entrytype","entrytype","entrytypename");

	dictCtrl.dictionary.load("nation","tradecountry","tradecountryname");
	dictCtrl.dictionary.load("nation","districtcode","districtcodename");
	dictCtrl.dictionary.load("nation","distinateport","distinateportname");

	decHeadEditCtrl.decHeadEdit.event();
	decHeadEditCtrl.decHeadEdit.initView();

	decHeadEditCtrl.decListEdit.event();
	decHeadEditCtrl.decLicenseEdit.event();
    decHeadEditCtrl.decContainerEdit.event();

	$('#iedate').datetimepicker({
		format: 'yyyy-mm-dd',
		language:  'zh-TW',
		weekStart: 1,
		todayBtn:  1,
		autoclose: 1,
		todayHighlight: 1,
		startView: 2,
		minView: 2,
		forceParse: 0
	});
	$('#decdate').datetimepicker({
		format: 'yyyy-mm-dd',
		language:  'zh-TW',
		weekStart: 1,
		todayBtn:  1,
		autoclose: 1,
		todayHighlight: 1,
		startView: 2,
		minView: 2,
		forceParse: 0
	});
});